import axios, { AxiosResponse } from "axios";
import Tools from "@/tool/Tools.ts";
import DictionaryConstants from "@/const/DictionaryConstants.ts";
import { ResponseData } from "@/model/AxiosModel.ts";
import { ElMessage, ElNotification } from "element-plus";
import router from "@/router/router.ts";
import qs from "qs";


// 创建axios实例并初始化默认配置
export const instance = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 5000,
    headers: {
        "Content-Type": "application/json",
        // 自定义请求头，表示是否添加 Token
        "IS_ADD_TOKEN": DictionaryConstants.AxiosConfigConst.IS_ADD_TOKEN.TRUE.value,
        // 自定义请求头，表示是否显示加载遮罩
        "IS_SHOW_LOADING": DictionaryConstants.AxiosConfigConst.IS_SHOW_LOADING.TRUE.value,
        // 自定义请求头，表示是否显示消息提示
        "IS_SHOW_MESSAGE": DictionaryConstants.AxiosConfigConst.IS_SHOW_MESSAGE.TRUE.value,
        // 自定义请求头，表示是否显示通知
        "IS_SHOW_NOTIFICATION": DictionaryConstants.AxiosConfigConst.IS_SHOW_NOTIFICATION.FALSE.value,
    },
});

// 配置请求参数序列化
instance.defaults.paramsSerializer = function(params) {
    //数组序列化
    return qs.stringify(params, { arrayFormat: "repeat", allowDots: true });
};


//请求拦截器
instance.interceptors.request.use(config => {
        // console.log(`请求拦截器${JSON.stringify(config)}`);
        const { IS_ADD_TOKEN, IS_SHOW_LOADING, IS_SHOW_MESSAGE } = config.headers;
        //如果请求头中有IS_ADD_TOKEN，则添加token
        if (Tools.StringTool.strToBool(IS_ADD_TOKEN) === DictionaryConstants.AxiosConfigConst.IS_ADD_TOKEN.TRUE.value) {
            config.headers.Token = JSON.parse(localStorage.getItem("UserInfoVo")).token;
        }
        //如果请求头中有IS_SHOW_LOADING，则开启遮罩
        if (Tools.StringTool.strToBool(IS_SHOW_LOADING) === DictionaryConstants.AxiosConfigConst.IS_SHOW_LOADING.TRUE.value) {
            Tools.LoadingTool.showLoading();
        }
        // if (Tools.StringTool.strToBool(IS_SHOW_MESSAGE)===DictionaryConstants.AxiosConfigConst.IS_SHOW_MESSAGE.TRUE.value){
        //     Tools.MessageTool.showLoading();
        // }
        return config;
    },
    error => {
        console.log("进入请求错误逻辑:", error);
        //关闭遮罩
        setTimeout(() => {
            Tools.LoadingTool.hideLoading();
        }, 800);

        //提示前端请求错误信息
        ElMessage.error("请求出错");
        //打印错误信息
        console.log(error);
    },
);
// 响应拦截器
instance.interceptors.response.use(
    (res: AxiosResponse) => {
        const { IS_SHOW_LOADING, IS_SHOW_MESSAGE, IS_SHOW_NOTIFICATION } = res.config.headers;
        const loadingEnabled = Tools.StringTool.strToBool(IS_SHOW_LOADING);
        const messageEnabled = Tools.StringTool.strToBool(IS_SHOW_MESSAGE);
        const notificationEnabled = Tools.StringTool.strToBool(IS_SHOW_NOTIFICATION);

        // 关闭遮罩
        if (loadingEnabled) {
            //1.5秒之后关闭遮罩
            setTimeout(() => {
                Tools.LoadingTool.hideLoading();
            }, 500);
        }

        const responseData: ResponseData<any> = res.data;

        if (responseData.code === DictionaryConstants.AxiosResCodeConst.SUCCESS.value) {
            if (messageEnabled) {
                ElMessage.success(`${responseData.msg}, 共${responseData.total}条数据`);
            }
            if (notificationEnabled) {
                ElNotification.success({
                    title: "成功",
                    message: responseData.msg,
                });
            }
        } else if (responseData.code === DictionaryConstants.AxiosResCodeConst.UNAUTHORIZED.value) {
            console.log("未授权");
            if (messageEnabled) {
                ElMessage.error(responseData.msg);
            }
            router.push(DictionaryConstants.RouterPathConst.LOGIN.path);
        } else {
            if (messageEnabled) {
                ElMessage.error(responseData.msg);
            }
            if (notificationEnabled) {
                ElNotification.error({
                    title: "失败",
                    message: responseData.msg,
                });
            }
        }

        return res.data;
    },
    (error) => {
        console.log("进入响应错误逻辑:", error);

        // 关闭遮罩
        Tools.LoadingTool.hideLoading();

        // 提示前端请求错误信息
        ElMessage.error("网络出错");

        // 打印错误信息
        console.error(error);

        return Promise.reject(error);
    },
);
export default instance;

//
// export {
//     getName,
// };